package com.weds.frame.auth.manager;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.weds.frame.auth.service.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.sql.Timestamp;
import java.util.Arrays;

/**
 * Description:
 * Author: LiuWenQing
 * Datetime: 2023/3/20 14:10
 */
@Component
@Slf4j
public class MetaDataHandler implements MetaObjectHandler {

    @Autowired
    private TokenUtil tokenUtil;

    @Override
    public void insertFill(MetaObject metaObject) {
        Object originalObject = metaObject.getOriginalObject();
        Class cla = originalObject.getClass();
        Class parentCla = cla.getSuperclass();
        Field[] declaredFields = cla.getDeclaredFields();
        Field[] parentDeclaredFields = parentCla.getDeclaredFields();
        if (tokenUtil.getUserId() != null) {
            if(Arrays.stream(declaredFields).filter(e->e.getName().equals("ctUserId")).findAny().isPresent()
                || Arrays.stream(parentDeclaredFields).filter(e->e.getName().equals("ctUserId")).findAny().isPresent()){
                this.strictInsertFill(metaObject, "ctUserId", () -> tokenUtil.getUserId(), Integer.class);
            }
            if(Arrays.stream(declaredFields).filter(e->e.getName().equals("ltUserId")).findAny().isPresent()
                    || Arrays.stream(parentDeclaredFields).filter(e->e.getName().equals("ltUserId")).findAny().isPresent())
                this.strictUpdateFill(metaObject, "ltUserId", () -> tokenUtil.getUserId(), Integer.class);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Object originalObject = metaObject.getOriginalObject();
        Class cla = originalObject.getClass();
        Class parentCla = cla.getSuperclass();
        Field[] declaredFields = cla.getDeclaredFields();
        Field[] parentDeclaredFields = parentCla.getDeclaredFields();
        if (tokenUtil.getUserId() != null) {
            if(Arrays.stream(declaredFields).filter(e->e.getName().equals("ltUserId")).findAny().isPresent()
                    || Arrays.stream(parentDeclaredFields).filter(e->e.getName().equals("ltUserId")).findAny().isPresent())
                this.strictUpdateFill(metaObject, "ltUserId", () -> tokenUtil.getUserId(), Integer.class);
            if(Arrays.stream(declaredFields).filter(e->e.getName().equals("ltDate")).findAny().isPresent()
                    || Arrays.stream(parentDeclaredFields).filter(e->e.getName().equals("ltDate")).findAny().isPresent())
                this.strictUpdateFill(metaObject, "ltDate", () -> new Timestamp(System.currentTimeMillis()), Timestamp.class);
        }
    }
}
